package com.hopes.bizz.poll.statistic.controller;

import com.alibaba.excel.EasyExcel;
import com.hopes.bizz.poll.analy.dto.ReportDTO;
import com.hopes.bizz.poll.statistic.service.DataReportService;
import com.hopes.bizz.poll.statistic.service.support.ReportExportSupport;
import com.hopes.boss.common.core.util.R;
import com.hopes.boss.common.log.annotation.SysLog;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;

/**
 * @author yumr
 * @Description 数据报表分析
 * @time 2023/6/6 9:15
 */
@Slf4j
@RestController
@RequiredArgsConstructor
@RequestMapping("/report" )
@Tag(description = "report" , name = "数据报表分析" )
@SecurityRequirement(name = HttpHeaders.AUTHORIZATION)
public class DataReportController {

    private final DataReportService dataReportService;
    private final ReportExportSupport reportExportSupport;

    @Operation(summary = "数据报表分析", description = "数据报表分析")
    @SysLog("数据报表分析" )
    @PostMapping("/analyze")
    @PreAuthorize("@pms.hasPermission('poll_report_analyze_view')" )
    public R reportAnalyze(@RequestBody ReportDTO reportDTO) {
        return R.ok(dataReportService.reportAnalyze(reportDTO));
    }

    @Operation(summary = "数据报表导出", description = "数据报表导出")
    @SysLog("数据报表导出")
    @GetMapping("export")
    public void reportExport(ReportDTO reportDTO, HttpServletResponse response) throws IOException {
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Accept-Ranges", "bytes");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8");
        EasyExcel
                .write(response.getOutputStream())
                .sheet()
                .head(reportExportSupport.reportHead(reportDTO.getMonitorSiteId()))
                .useDefaultStyle(true).relativeHeadRowIndex(2)
                .doWrite(reportExportSupport.reportDataList(reportDTO));
    }
}
